package com.wyc.alipay.controller;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.wyc.alipay.service.AlipayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequestMapping("/alipay")
@Controller
public class AlipayController {

    @Autowired
    private AlipayService alipayService;

    /**
     *  支付
     * @param subject 主题
     * @param outTradeNo 交易流水号
     * @param totalAmount 支付金额
     * @return
     */
    @GetMapping("/pay")
    @ResponseBody
    public String pay(@RequestParam("subject") String subject,@RequestParam("outTradeNo") String outTradeNo,@RequestParam("totalAmount") String totalAmount){
        AlipayTradePagePayResponse response;
        try {
            response = Factory.Payment.Page().pay(subject,outTradeNo,totalAmount,"");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return response.getBody();
    }

    /**
     * test支付宝回调
     * @return
     */
    @PostMapping("/notify")
    @ResponseBody
    public String notify(HttpServletRequest request) throws Exception {
        String tradeStatus = request.getParameter("trade_status");
        // 如果交易完成
        if (tradeStatus.trim().equals("TRADE_SUCCESS")){
            HashMap<String, String> param = new HashMap<>();
            Map<String, String[]> parameterMap = request.getParameterMap();
            for (String name: parameterMap.keySet()){
                param.put(name,request.getParameter(name));
            }

            if (Factory.Payment.Common().verifyNotify(param)){
                log.info("通过支付宝的验证");
                // 验签通过，调用order服务，修改订单状态
                String outTradeNo = param.get("out_trade_no");
                Long orderId = Long.parseLong(outTradeNo);
                alipayService.pay(orderId);
            }else {
                log.info("支付宝验证 不通过！");
            }

        }

        return "success";
    }



}
